package com.weipai.springboot.shiro;

import com.alibaba.fastjson.JSONObject;
import com.weipai.springboot.model.Customer;
import com.weipai.springboot.model.sys.User;
import com.weipai.springboot.module.util.SessionUserUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;

/**
 * @author songmengqiang
 * @create 2018-09-20 11:52
 **/
@Repository
public class AppCacheDao {
    private static final Logger logger = LoggerFactory.getLogger(AppCacheDao.class);
    private static final String cacheName = "appUserChache";

    @Autowired
    private EhCacheCacheManager enCacheManager;

    private Cache cache;


    @PostConstruct
    private void init() {
        cache = enCacheManager.getCacheManager().getCache(cacheName);
    }

    public void save(String key, User user) {
        Element element = new Element(key, user);
        cache.put(element);
        cache.flush();
    }

    public User getUser(String key) {
        Element element = cache.get(key);
        logger.info("AppCacheDaogetUserelement:"+ JSONObject.toJSONString(element));
        if(element!=null){
            return (User) element.getObjectValue();
        }
        return null;
    }

    public void deleteUser(String key) {
        cache.remove(key);
    }
}
